param ( [string] $DataSetDirectory
      , [string] $ConfigFile=$DefaultDatabaseConfigFile
      , [string] $EnvironmentName=$DefaultDatabaseEnv
			, [string] $ServerName=$DefaultServerName
			, [string] $DatabaseName=$DefaultDatabaseName
			, [string] $Username=$DefaultUsername
			, [string] $Password=$DefaultPassword
			)

. Resolve-DbDeploymentParms

if ($DataSetDirectory -eq "")
{
	 $DataSetDirectory = Join-path $SchemaDir "Datasets"
}

$connection = $PSSqlConnectionClass.New($ProviderParms)

try {
	$cmd = $PSSqlCommandClass.New($connection)
	
	$allfileNames = Get-ChildItem $DataSetDirectory | where{$_ -is [system.io.fileinfo]} | %{$_.Name}
	$DataSetFileNames = $allfileNames | where{$_ -match ".+\..+\.xml"} 
	$ExcludedFiles = $allfileNames | where {$DataSetFileNames -notcontains $_}
	$DataSetTables = $DataSetFileNames | %{$_ -replace ".xml",""}
	
	foreach ($DataSetTable in $DataSetTables)
	{
		if ($DataSetTable -match "^(?'schema'.*)\.(?'table'.*)$")
		{
			$schema = $matches.schema
			$tablename = $matches.table
			
			
			$query = "SELECT * FROM [{0}].[{1}] FOR XML AUTO, ROOT('ROOT')" -f $schema,$tablename
			$doc = $cmd.LoadAndExecuteXmlQuery($query)
			$content = @()
			$outputFile = "$DataSetDirectory\$schema.$tablename.xml"
			
			if ($doc.Root -ne $null)
			{
				foreach( $element in $doc.Root.GetEnumerator())
				{
					$content += $element.get_OuterXML()
				}
				$content | Set-Content $outputFile 
			}
			else
			{
				$null | Set-Content $outputFile 
			}
			Log-Message "Writing to: $outputFile"
		}
		else
		{
			Throw "Invalid Dataset name '$DataSetTable' - must be 'schema.tablename'"
		}
	}
	$ExcludedFiles | %{Log-Warning "'$_' does not match pattern of '<schema>.<tablename>.xml'"}
} -finally {
	$connection.connection.Close()
}

